//
//  MCHealthManager.m
//  MoveVirtualCurrency
//
//  Created by LiuYing on 2018/6/6.
//  Copyright © 2018年 Test. All rights reserved.
//

#import "MCHealthManager.h"
#import <HealthKit/HealthKit.h>
#import "SSKAlertHelper.h"
#import "MCHealthUtil.h"
#import "NSObject+SSKExtension.h"

#import <XYQuick.h>
#import <MJExtension.h>

// 日期
#define kHealthQueryResultDateKey   @"date"

// 步数
#define kHealthQueryResultStepsKey  @"step"

#pragma mark -
#define MCGetMethodReturnObjc(objc) if (objc) return objc

@interface MCHealthManager ()

@property (nonatomic, strong) HKHealthStore *healthStore;

@property (nonatomic, copy) MCHealthReadBlock handler;
//
@property (nonatomic, copy) MCHealthReadResults results;


@property (nonatomic, assign) MCHealthQueryType queryType;
@property (nonatomic, assign) MCHealthResultSort resultSort;

@end

@implementation MCHealthManager

+ (instancetype)defaultManager {
    
    static MCHealthManager *sharedManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[[self class] alloc] init];
    });
    
    return sharedManager;
}

- (HKHealthStore *)healthStore {
    MCGetMethodReturnObjc(_healthStore);
    _healthStore = [[HKHealthStore alloc] init];
    return _healthStore;
}


- (NSSet *)dataTypesRead {
    HKQuantityType *stepCountType = [self sampleStepCount];
    return [NSSet setWithObjects:stepCountType, nil];
}

- (HKQuantityType *)sampleStepCount {
    return [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
}

- (NSArray *)sortDescriptors {
    
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    
    NSArray *descriptors = @[start,end];
    
//    if (self.resultSort == MCHealthResultSortObverse) {
//        sortDescriptors = @[end, start];
//    }
    
    return descriptors;
}


- (BOOL)isHealthDataAvailable {
    return [HKHealthStore isHealthDataAvailable];
}

#pragma mark - 读取步数 查询数据
#pragma mark -

- (HKAuthorizationStatus)authorizationStatus {
    return [self.healthStore authorizationStatusForType:[self sampleStepCount]];
}

- (void)checkAuthor {
    
    HKAuthorizationStatus status = self.authorizationStatus;
    switch (status) {
        case HKAuthorizationStatusNotDetermined: {
            // 未询问

            NSLog(@"HKAuthorizationStatusNotDetermined");
            
            [self showAlert:@"同步健康里的步数到智康宝，我们会将步数上传到智康链，即可获取智康钻。如果你同意同步，将默认同意上传到智康链，如果不同步，你可能将不能正常获取智康钻"
                    handler:^(UIAlertAction * _Nonnull action) {
                        if (action.style == UIAlertActionStyleCancel) {
                            [self requestAuthor];
                        }
                    }];


        }
            break;
        case HKAuthorizationStatusSharingDenied: {
            //
            NSLog(@"HKAuthorizationStatusSharingDenied");
            
           // [self authorStatusSharingDenied];
            [self requestAuthor];
        }
            break;
        case HKAuthorizationStatusSharingAuthorized: {
            // 同意
            NSLog(@"HKAuthorizationStatusSharingAuthorized");
            [self requestAuthor];
        }
            break;
            
        default:
            break;
    }
}

- (void)authorStatusSharingDenied {
    
    NSString *message = @"你未同步数据到智康宝，不能获取智康钻，若要获取智康钻，请打开系统健康应用，数据来源->应用，同意同步数据至智康宝，即可开始获取智康钻";
    [SSKAlertHelper showAlert:@"提示"
                      message:message
                  cancelTitle:@"知道了"
                      handler:nil];
}

- (void)showAlert:(NSString *)message
          handler:(void (^)(UIAlertAction * _Nonnull action))handler {
    
    [SSKAlertHelper showAlert:@"提示"
                      message:message
                  cancelTitle:@"前往同步"
                  otherTitles:@[@"暂不同步"]
                      handler:handler];
}

- (void)requestAuthor {
    
    [self.healthStore requestAuthorizationToShareTypes:nil
                                             readTypes:[self dataTypesRead]
                                            completion:^(BOOL success, NSError * _Nullable error) {
                                                
//                                                HKAuthorizationStatus status = self.authorizationStatus;
//                                                if (status == HKAuthorizationStatusSharingDenied) {
//
//                                                    // 拒绝
//
//                                                     [self authorStatusSharingDenied];
//
//                                                    [self ssk_dispatch_async_main:^{
//                                                        if (self.handler) {
//                                                            self.handler(MCHealthQuerySetupError, error);
//                                                        }
//                                                    }];
//
//
//
//                                                } else {
                                                
                                                [self authorizationResultHandler:success error:error];
                                                
//                                                }
                                                

                                                
                                            }];
}

- (void)authorizationResultHandler:(BOOL)success
                             error:(NSError *)error {
    if (success) {
        [self querySetupInHealthStore];
    } else {
        
        [self ssk_dispatch_async_main:^{
            if (self.handler) {
                self.handler(MCHealthQuerySetupError, error);
            }
        }];
        NSLog(@"%@", error.localizedDescription);
        
        [SSKAlertHelper showAlert:@"提示"
                          message:error.localizedDescription
                      cancelTitle:@"好"
                          handler:nil];
    }
    
}


- (void)readTodayStepCount:(void (^)(NSInteger, NSError * _Nullable))result {
    //if (![MCAppSettings isLogin]) return;
    
    self.resultSort = MCHealthResultSortReverse;
    self.queryType = MCHealthQueryTypeToday;
    self.handler = result;
    
    [self checkAuthor];
    
}

- (void)readLastSevenDaysStepCount:(MCHealthReadResults)results {
    [self readStepCount:MCHealthQueryTypeLastSevenDays
                results:results];

}

- (void)readLastThirtyDaysStepCount:(MCHealthReadResults)results {
    [self readStepCount:MCHealthQueryTypeLastThirtyDays
                results:results];
}

- (void)readStepCount:(MCHealthQueryType)queryType
              results:(MCHealthReadResults)results {
    //if (![MCAppSettings isLogin]) return;
    
    self.queryType = queryType;
    self.results = results;
    
    [self checkAuthor];
}

- (void)readStepsWithQueryType:(MCHealthQueryType)queryType
                          sort:(MCHealthResultSort)sort
                       results:(MCHealthReadResults)results {
    if (queryType == MCHealthQueryTypeToday) {
        return;
    }
    
    self.resultSort = sort;
    [self readStepCount:queryType results:results];
    
}


- (void)querySetupInHealthStore {
    
    //查询采样信息
    HKSampleType *sampleType = [self sampleStepCount];
    
    //排序条件
    NSArray *sortDescriptors =  [self sortDescriptors];
    
    // 查询语句
    NSPredicate *predicate = [self queryPredicate];
    
    /* 构造一个HKSample类所以对应的查询类是HKSampleQuery。
       limit参数传1表示查询最近一条数据
     */
    
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType
                                                                 predicate:predicate
                                                                     limit:0
                                                           sortDescriptors:sortDescriptors
                                                            resultsHandler:^(HKSampleQuery * _Nonnull query,
                                                                             NSArray<__kindof HKSample *> * _Nullable results,
                                                                             NSError * _Nullable error) {
                                                                [self queryResultsHandler:results error:error];
                                                            }];
    
    //执行查询
    [self.healthStore executeQuery:sampleQuery];
}

- (void)queryResultsHandler:(NSArray<__kindof HKSample *> *)results
                      error:(NSError *)error {
    if (error) {
        if (self.handler) {
            [self ssk_dispatch_async_main:^{
                self.handler(MCHealthQuerySetupError, error);
            }];
        }
    } else {
        
        if (results.count <= 0) {
            // 如果0步，下个版本处理
            [self ssk_dispatch_async_main:^{
                //[self authorStatusSharingDenied];
            }];
            return;
        }
        
        [self parseResults:results completion:^(NSArray<NSDictionary *> *steps) {
            
            [self ssk_dispatch_async_main:^{
                
                if (self.queryType == MCHealthQueryTypeToday) {
                    NSDictionary *dictionary = steps.firstObject;
                    NSInteger setupCount = [dictionary[kHealthQueryResultStepsKey] integerValue];
                    if (self.handler) {
                        self.handler(setupCount, nil);
                    }
                }
                
                
                if (self.queryType == MCHealthQueryTypeLastSevenDays ||
                    self.queryType == MCHealthQueryTypeLastThirtyDays) {
                    if (self.results) {
                        self.results([MCStepItem mj_objectArrayWithKeyValuesArray:steps], nil);
                    }
                    
                }
                
            }];
        }];
        
    }
}


- (void)parseResults:(NSArray<__kindof HKSample *> *)results
          completion:(void (^)(NSArray <NSDictionary *> *steps))completion {
    
    
    __block int allStepCount = 0;
    __block NSString *dateString = nil;
    
    NSMutableArray *steps = [NSMutableArray array];
    
    [results enumerateObjectsUsingBlock:^(__kindof HKSample * _Nonnull sample,
                                          NSUInteger idx,
                                          BOOL * _Nonnull stop) {
        //把结果转换为字符串类型
        HKQuantitySample *result = sample;
        HKQuantity *quantity = result.quantity;
        NSMutableString *stepCount = (NSMutableString *)quantity;
        NSString *stepStr = [NSString stringWithFormat:@"%@",stepCount];
        
        //获取步数 count此类字符串前面的数字
        NSString *str = [stepStr componentsSeparatedByString:@" "][0];
        int stepNum = [str intValue];
        
        
        NSString *tmpDateString = [result.startDate uxy_stringWithDateFormat:@"yyyy.MM.dd"];
        if (dateString) {
            if ([tmpDateString isEqualToString:dateString]) {
                //把一天中所有时间段中的步数加到一起
                allStepCount = allStepCount + stepNum;
            } else {
                
                NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
                if (tmpDateString.length) {
                    [dictionary setValue:dateString forKey:kHealthQueryResultDateKey];
                    [dictionary setValue:@(allStepCount) forKey:kHealthQueryResultStepsKey];
                }
                
                [steps addObject:dictionary];
                allStepCount = stepNum;
            }
        } else {
            // 第一次
            allStepCount = stepNum;
        }
        
        dateString = tmpDateString;
    }];
    

    
    if (dateString && steps.count <= 0) {
        // 只有一天
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        [dictionary setValue:dateString forKey:kHealthQueryResultDateKey];
        [dictionary setValue:@(allStepCount) forKey:kHealthQueryResultStepsKey];
        [steps addObject:dictionary];
    }
    
    if (self.queryType == MCHealthQueryTypeLastSevenDays ||
        self.queryType == MCHealthQueryTypeLastThirtyDays) {
        // 最后一天
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        [dictionary setValue:dateString forKey:kHealthQueryResultDateKey];
        [dictionary setValue:@(allStepCount) forKey:kHealthQueryResultStepsKey];
        [steps addObject:dictionary];
    }

    
    if (completion) {
        if (self.resultSort == MCHealthResultSortObverse) {
            NSMutableArray *tmp = [NSMutableArray array];
            [steps enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [tmp addObject:obj];
            }];
            
            steps = tmp;
        }
        completion(steps);
    }
}


#pragma mark - query predicate
#pragma mark -

- (NSPredicate *)queryPredicate {
    
    NSPredicate *predicate = nil;
    if (self.queryType == MCHealthQueryTypeToday) {
        predicate = [MCHealthUtil todaySetupCountPredicate];
    } else if (self.queryType == MCHealthQueryTypeLastSevenDays) {
        predicate = [MCHealthUtil lastSevenDaysSetupCountPredicate];
    } else if (self.queryType == MCHealthQueryTypeLastThirtyDays) {
        predicate = [MCHealthUtil lastThirtyDaysStepCountPredicate];
    }
    
    return predicate;
}



@end
